package org.example;

import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.WritableImage;
import javafx.scene.web.WebView;
import javafx.concurrent.Worker;
import javafx.util.Duration;
import javafx.animation.PauseTransition;
import tech.tablesaw.plotly.Plot;
import tech.tablesaw.plotly.components.Figure;
import tech.tablesaw.plotly.components.Page;

import javax.imageio.ImageIO;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

public class FigureToImageConverter2 {

    public static void main(String[] args) throws Exception {
//
//        Figure[] charts = IMRControlChart.getChats(new String[]{});
//        // 示例: 创建一个简单的图表
//        Figure figure = charts[0];// 你的Figure创建代码
//
//            boolean success = convertToImage(
//                    figure,
//                    new File("output.png"),
//                    800,
//                    600,
//                    "png"
//            );

    }

    public static boolean convertToImage(Figure figure, File outputFile,
                                         int width, int height, String format)
            throws InterruptedException {

        if (!Platform.isFxApplicationThread()) {
            AtomicBoolean toolkitInitialized = new AtomicBoolean(false);
            CountDownLatch latch = new CountDownLatch(1);

            Platform.startup(() -> {
                toolkitInitialized.set(true);
                latch.countDown();
            });

            latch.await();
            if (!toolkitInitialized.get()) {
                return false;
            }
        }

        File tempHtml = createTempHtml(figure);
        if (tempHtml == null) {
            return false;
        }

        CountDownLatch screenshotLatch = new CountDownLatch(1);
        AtomicBoolean success = new AtomicBoolean(false);

        Platform.runLater(() -> {
            WebView webView = new WebView();
            webView.setPrefSize(width, height);
            webView.getEngine().setJavaScriptEnabled(true);
            webView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
                if (newState == Worker.State.SUCCEEDED) {
                    PauseTransition pause = new PauseTransition(Duration.seconds(1)); // 1秒延迟
                    pause.setOnFinished(event -> {
                        try {
                            WritableImage image = new WritableImage(width, height);
                            webView.snapshot(null, image);
                            ImageIO.write(SwingFXUtils.fromFXImage(image, null), format, outputFile);
                            success.set(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            screenshotLatch.countDown();
                            tempHtml.delete();
                        }
                    });
                    pause.play();
                }
            });

            try {
                webView.getEngine().load(tempHtml.toURI().toURL().toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
                screenshotLatch.countDown();
            }
        });

        screenshotLatch.await();
        return success.get();
    }

    private static File createTempHtml(Figure figure) {
        try {
            File tempFile = File.createTempFile("tablesaw-", ".html");
            tempFile.deleteOnExit();
            String html = write(figure);
            System.out.println(html);
            Files.write(tempFile.toPath(), html.getBytes());
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected static final String DEFAULT_DIV_NAME = "target";


    public static String write(Figure figure) {
        return write(figure, DEFAULT_DIV_NAME);
    }


    public static String write(Figure figure, String divName) {
        Page page = Page.pageBuilder(figure, divName).plotlyJsLocation("./plotly-latest.min.js").build();
        String output = page.asJavascript();
        return output;
    }

}